package 晚间作业0419

import scala.io.Source


object Scala_02 {
  def main(args: Array[String]): Unit = {
    studentStatics
    println()
    example02
    println()
    example03
  }

  /**
   * 2.现有学⽣成绩数据a.txt⽂件，请统计各学科平均分、最低分、最⾼分。
   */
  def studentStatics = {
    //1、读取文件
    val source = Source.fromFile("file/0419/a.txt")
    val lines = source.getLines()
    lines.next // 跳过表头
    val list = lines.toList.map(_.split("\\s+")) // 3、切分每一项
    def printStaticsResult(info: List[Double]) = {
      println(s"最高分: ${info.max}")
      println(s"最低分: ${info.min}")
      println(s"平均分: ${info.sum / info.length}")
    }
    println("===========数学相关===========")
    printStaticsResult(list.map(_ (2).toDouble))
    println("===========英语相关===========")
    printStaticsResult(list.map(_ (3).toDouble))
    println("===========物理相关===========")
    printStaticsResult(list.map(_ (4).toDouble))
    source.close()
  }


  /**
   * 实战案例⼆
   */
  def example02 = {
    val source = Source.fromFile("file/0419/yq.csv")
    val lines = source.getLines()
    lines.next
    lines.toList
      .map(_.split(","))
      .groupBy(_(0))
      .map(group => {
        val max = group._2.maxBy(_(2))
        (group._1, max(1), max(2))
      }).toList.sortBy(_._1)
      .foreach(println)
    source.close
  }

  def example03 = {
    val sourceOrders = Source.fromFile("file/0419/orders.csv")
    val sourceItems = Source.fromFile("file/0419/order_item.csv")

    val lineOrders = sourceOrders.getLines
    lineOrders.next
    val orderList = lineOrders.toList

    val lineItems = sourceItems.getLines
    lineItems.next
    val itemList = lineItems.toList

    // 统计未⽀付的订单数量
    val orders = orderList.map(_.split("\\s+"))
    println(s"1、未消费的订单数量为: ${orders.count(_ (4) == "PENDING_PAYMENT")}")
    val groupByOrderId: Map[String, List[Array[String]]] = itemList.map(_.split("\\s+")).groupBy(_(1))
    // 每个订单的商品列表（包含哪些商品）
    println("2、每个订单的商品id列表为: ")
    groupByOrderId
      .view
      .mapValues(_.map(_(2)))
      .foreach(println)
    // 每个订单的总⾦额
    println("3、每个订单的总金额为: ")
    val totalList = groupByOrderId
      .view
      .mapValues(_.map(_(4).toDouble))
      .map(item => {
        (item._1, item._2.sum)
      }).toList.sortBy(_._1)
    totalList.foreach(println)
    // 找出消费最多的客户
    val customerId = orders.filter(_(4) != "PENDING_PAYMENT")
      .map(order => {
        (order(3), totalList.filter(_._1 == order(0)).map(_._2).sum)
      }).groupBy(_._1)
      .view
      .mapValues(_.map(_._2).sum)
      .maxBy(_._2)._1
    println(s"4、消费最多的客户Id为: $customerId")
    sourceOrders.close
    sourceItems.close
  }
}
